# Draw the density graphs (loan size, appraisal value)
# Loanamt density is drawn from eMBS data (since the matched data is truncated
#  using  appraisal value)

bin_size <- 1.25 
bin_size2 <- 2.5

barfill <- "#4271AE"
barlines <- "#1F3552"

library(tidyverse)
library(haven)
library(magrittr)
library(lubridate)
library(grid)
library(gridExtra)

source("/tr/proj9/m1yxh01/programs/R/stata_ym_to_R_date.R")

rootdir <- dirname(getwd())
scratchdir <- file.path(rootdir, "data", "scratch_data")
tempdir <- file.path(scratchdir, "temp")
outdir <- file.path(rootdir, "TEX", "Figures")

loansize_sample <- read_dta(file.path(tempdir, "embs-prep.dta")) %>%
  mutate(loanamt_adj = (orig_loan_amount - 417000)/1000)

cll_sample <- read_dta(file.path(tempdir, "embs-lps-matched.dta")) %>%
  mutate(loanamt_adj = (orig_loan_amount - 417000)/1000,
         appraisal_adj = (appraisal_amount - 417000 * 1.25)/1000)

loansize_sample <- loansize_sample %>%
  mutate(orig_ym2 = stata_ym_to_R_date(orig_ym)) %>%
  filter(agency_id == 2 | orig_ym2 >= as.Date("2011-11-01"))

# FNM loans are restricted to loans issued on or after 2011M11 as mentioned in text
cll_sample <- cll_sample %>%
  mutate(orig_ym2 = stata_ym_to_R_date(orig_ym)) %>%
  filter(agency_id == 2 | orig_ym2 >= as.Date("2011-11-01"))

ggplot(subset(loansize_sample, -150 < loanamt_adj & loanamt_adj <= 150),
       aes(x = loanamt_adj, y = ..count../sum(..count..))) +
  stat_bin(binwidth = bin_size2, closed = "right", boundary = 0,
           color = barlines, fill = barfill, lwd = 0.3) +
  xlab("Loan Size \u2013 CLL ($1,000)") + theme_bw() +
  theme(axis.title.y = element_blank(),
        plot.background = element_rect(fill = "gray92")) +
  ggsave(file.path(outdir, "20210322_CLL_loanamt_density.pdf"),
         width = 5, height = 4, device = cairo_pdf)

ggplot(subset(cll_sample, -150 < appraisal_adj & appraisal_adj <= 150),
       aes(x = appraisal_adj, y = ..count../sum(..count..))) +
  stat_bin(binwidth = bin_size, closed = "right", boundary = 0,
           color = barlines, fill = barfill, lwd = 0.3) +
  xlab("Appraisal Value \u2013 1.25 CLL ($1,000)") + theme_bw() +
  theme(axis.title.y = element_blank(),
        plot.background = element_rect(fill = "gray92")) +
  ggsave(file.path(outdir, "20210322_CLL_appraisal_density.pdf"),
         width = 5, height = 4, device = cairo_pdf)

